package com.book.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.book.auth.JwtUtil;
import com.book.core.mode.SysLoginUser;
import com.book.auth.service.LoginService;
import com.book.core.dto.LoginDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final RedisTemplate<String,String> redisTemplate;
    @Override
    public Map<String,Object> login(LoginDTO loginDTO) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDTO.getUserName(),loginDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //使用userid生成token
//        查询成功
        SysLoginUser loginUser = (SysLoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSysUser().getUserId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisTemplate.opsForValue().set("loginUser:"+userId, JSON.toJSONString(loginUser));
        //把token响应给前端
        HashMap<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("user",loginUser.getSysUser());
        map.put("roles",loginUser.getRoles());
        map.put("menus",loginUser.getMenus());
        return map;
    }
    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SysLoginUser loginUser = (SysLoginUser) authentication.getPrincipal();
        Integer userid = loginUser.getSysUser().getUserId();
        redisTemplate.delete("loginUser:"+userid);
    }
}
